package com.boxuegu.controller;

import com.boxuegu.domain.Fruit;
import com.boxuegu.service.UserService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class UserController {
    private UserService userService = new UserService();
    private Scanner sc = new Scanner(System.in);
    private String choice;
    private ArrayList<Fruit> fruits;
    private HashMap<Fruit, Integer> cat = new HashMap<>();

    public UserController() throws IOException {
    }

    //开启用户系统
    public void start() throws IOException, ClassNotFoundException {
        //展示菜单并获取用户键盘输入的选择
        lo:
        while (true) {
            System.out.println("=================欢迎来到水果超市管理系统=================");
            System.out.println("请输入您的选择：   ①登录   ②查看水果   ③开始购买    ④结账   ⑤退出");
            //接受用户键盘输入的选择
            choice = sc.next();
            switch (choice) {
                case "1":
                    //登录方法
                    login();
                    break;
                case "2":
                    //查看水果
                    lookFruit();
                    break;
                case "3":
                    //开始购买
                    System.out.println("请先登录！");
                    break;
                case "4":
                    //结账
                    System.out.println("请先登录！");
                    break;
                case "5":
                    //退出
                    break lo;
                default:
                    System.out.println("您的输入有误，请重新输入！");
                    break;

            }
        }
    }

    //登陆方法
    public void login() throws IOException, ClassNotFoundException {
        //键盘接收登录信息
        String id;  //用户ID
        String password;  //用户密码
        signForLogin:
        while (true) {
            System.out.println("请输入账号（输入n返回）");
            id = sc.next();
            if (id.equals("n")) {
                break signForLogin;  //如果输入了n，退出此次判断
            } else {
                System.out.println("请输入密码（输入n返回）");
                password = sc.next();
                if (password.equals("n")) {
                    break;
                } else {
                    boolean flag = userService.checkPassword(id, password); // 判断id和密码是否匹配
                    if (flag) {
                        System.out.println("登陆成功！");
                        //登录成功后调用进入已登录界面的方法
                        enter(id);
                        break;
                    } else {
                        System.out.println("账号或密码输入错误，请重新输入");
                        break;
                    }
                }
            }
        }
    }

    //登录成功后进入已登录界面
    private void enter(String id) throws IOException, ClassNotFoundException {
        signForEnter:
        while (true) {
            System.out.println("请输入您的选择：   ①查看水果   ②开始购买   ③结账   ④查看余额   ⑤清空购物车   ⑥退出");
            //接受用户键盘输入的选择
            choice = sc.next();
            switch (choice) {
                case "1":
                    //查看水果
                    lookFruit();
                    break;
                case "2":
                    //开始购买
                    buy(id);
                    //System.out.println("开始购买");
                    break;
                case "3":
                    //结账
                    if (cat != null && !cat.isEmpty()) {
                        pay(id);
                    } else {
                        System.out.println("请购买后再结账");
                    }
                    //System.out.println("结账");
                    break;
                case "4":
                    //查看余额
                    deposit(id);
                    break;
                case "5":
                    //清空购物车
                    cat.clear();
                    break;
                case "6":
                    //退出
                    System.out.println("退出");
                    cat.clear();
                    break signForEnter;
                default:
                    System.out.println("您的输入有误，请重新输入！");
                    break;
            }
        }
    }

    //查看余额方法
    private void deposit(String id) throws IOException, ClassNotFoundException {
        System.out.println("您当前的余额为" + userService.getMoney(id));
    }

    //查看水果方法
    void lookFruit() throws IOException, ClassNotFoundException {
        fruits = userService.findAllFruit();
        if (fruits != null) {
            System.out.println("编号      名称      价格      库存量");
            for (Fruit fruit : fruits) {
                System.out.println(fruit);
            }
        } else {
            System.out.println("没有水果了！");
        }
    }

    //购买水果方法
    private void buy(String id) throws IOException {
        lo_endBuy:
        while (true) {
            System.out.println("请输入水果名字（输入n返回）");
            String fruitName = sc.next();
            if (fruitName.equals("n")) {
                break;
            } else if (userService.isFruitExists(fruitName)) { //获取水果名是否存在的方法
                lo_number:
                while (true) {
                    System.out.println("请输入该水果数量（输入n返回）");
                    String strfruitnumber = sc.next();
                    if (strfruitnumber.equals("n")) {
                        break;
                    } else {
                        //如果用户输入的字符串不是数字，会出错
                        int fruitNumber = 0;  //把上面的水果数量转换成int类型
                        try {
                            fruitNumber = Integer.parseInt(strfruitnumber);
                        } catch (NumberFormatException e) {
                            System.out.println("输入错误，请输入您要购买的水果的数量");
                            continue;
                        }
                        if (fruitNumber <= 0) {
                            System.out.println("请输入正确的数量");
                        } else {
                            if (cat == null) {
                                if (fruitNumber <= userService.getFruitAmount(fruitName)) { // 获取水果库存量
                                    cat = userService.addFruitToShoppingBasket(fruitName, fruitNumber, cat);// 添加水果到购物车
                                    break;
                                } else {
                                    System.out.println("当前水果库存量无法满足您的要求，当前水果库存量为：" + userService.getFruitAmount(fruitName) + "，请重新输入");
                                }
                            } else {
                                int purchased = userService.getValue(fruitName,cat);
                                if (fruitNumber <= (userService.getFruitAmount(fruitName)-purchased)){
                                    cat = userService.addFruitToShoppingBasket(fruitName, fruitNumber, cat);// 添加水果到购物车
                                    break;
                                } else {
                                    System.out.println("当前水果库存量无法满足您的要求，当前水果库存量为：" + userService.getFruitAmount(fruitName) +"您已购买"+purchased+"该水果还剩余"+(userService.getFruitAmount(fruitName)-purchased)+"，请重新输入");
                                }
                            }
                        }
                    }
                }
            } else {
                System.out.println("水果不存在，请重新输入！");
                continue;
            }
            while (true) { //判断是否要继续购买
                System.out.println("如需继续购买输入y，结束购买输入n");
                String isBuy = sc.next();
                if (isBuy.equals("y")) {
                    break;
                } else if (isBuy.equals("n")) {
                    break lo_endBuy;
                } else {
                    System.out.println("请输入y或者n！");
                }
            }
        }

    }

    //结账方法
    private void pay(String id) throws IOException, ClassNotFoundException {
        System.out.println("您购买了以下水果，请查看确认");
        System.out.println("名称          数量           价格");
        Set<Fruit> keySet = cat.keySet();
        for (Fruit key : keySet) {
            int number = cat.get(key);
            System.out.println(key.getName() + "\t\t\t" + number + "\t\t\t" + key.getPrice());
        }
        System.out.println("总价为：" + userService.getPriceSum(cat) + "   经折扣后总价为：" + userService.getPriceDiscountSum(cat));
        while (true) {
            System.out.println("是否确认购买？y/确定,n/返回");
            String isPay = sc.next();
            if (isPay.equals("y")) {
                //定义一个判断水果库存是否足够的变量
                boolean isSufficient = true;
                for (Fruit fruit : keySet) {
                    if (fruit.getAmount() <= cat.get(fruit)) {
                        isSufficient = false;
                    }
                }
                if (userService.getPriceDiscountSum(cat) <= userService.getMoney(id)) {//获取顾客的余额
                    if (isSufficient) {
                        userService.pay(id, userService.getPriceDiscountSum(cat), cat);//花费余额，余额减少则输出购买成功！
                        System.out.println("支付成功");
                        cat.clear();
                        break;
                    } else {
                        System.out.println("水果库存不足，请重新选择！");
                        break;
                    }
                } else {
                    System.out.println("余额不足，请重新选择！");
                    break;
                }

            } else if (isPay.equals("n")) {
                break;
            } else {
                System.out.println("请输入y或者n！");
            }
        }

    }

}
